package com.hnx.admin.aurora.system.service.impl;

import com.hnx.admin.aurora.annotation.Pager;
import com.hnx.admin.aurora.annotation.RepeatValidator;
import com.hnx.admin.aurora.api.cache.CacheAPI;
import com.hnx.admin.aurora.enums.BusinessType;
import com.hnx.admin.aurora.redis.RedisCache;
import com.hnx.admin.aurora.system.domain.convert.PostConvert;
import com.hnx.admin.aurora.system.domain.dto.post.entity.SysPostDTO;
import com.hnx.admin.aurora.system.domain.dto.post.query.PostQuery;
import com.hnx.admin.aurora.system.domain.param.post.form.PostForm;
import com.hnx.admin.aurora.system.domain.vo.post.entity.SysPostVO;
import com.hnx.admin.aurora.system.mapper.post.SysPostMapper;
import com.hnx.admin.aurora.system.service.SysPostService;
import com.hnx.admin.aurora.web.json.ResultJson;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/*
创建人： 倔强的头发
创建时间：2025/6/18
功能描述:

*/
@Service
@RequiredArgsConstructor
public class SysPostServiceImpl implements SysPostService, CacheAPI {
    private final RedisCache redisCache;
    private final SysPostMapper sysPostMapper;
    private final PostConvert postConvert;
    @Override
    public List<SysPostVO> getPostList() {
        return redisCache.getCacheList(SYS_POST_KEY,SysPostVO.class).orElseGet(this::getList);
    }

    @Override
    @Pager
    public ResultJson selectPostList(PostQuery post) {
        List<SysPostDTO> list = sysPostMapper.selectPostList(post);
        return ResultJson.rows(list);
    }

    @Override
    @RepeatValidator
    public ResultJson insertPost(PostForm post) {
        int res = sysPostMapper.insertPost(post);
        deleteRedis(res);
        return ResultJson.condition(res);
    }

    @Override
    public ResultJson deletePostByIds(String[] postIds) {
        int res = sysPostMapper.countUserPostById(postIds);
        if(res > 0){
            throw new RuntimeException(String.format("岗位已分配用户,不能删除"));
        }
        int result = sysPostMapper.deletePostByIds(postIds);
        deleteRedis(result);
        return ResultJson.condition(result);
    }

    @Override
    public ResultJson selectPostById(String postId) {
        SysPostDTO postDTO = sysPostMapper.selectPostById(postId);
        return ResultJson.data(postDTO);
    }

    @Override
    @RepeatValidator(type = BusinessType.UPDATE)
    public ResultJson updatePost(PostForm post) {
        int res = sysPostMapper.updatePost(post);
        deleteRedis(res);
        return ResultJson.condition(res);
    }

    private List<SysPostVO> getList(){
        List<SysPostDTO> list = sysPostMapper.selectPostAll();
        List<SysPostVO> lst = postConvert.toVOList(list);
        redisCache.setCacheList(SYS_POST_KEY,lst);
        return lst;
    }
    private void deleteRedis(int result){
        if(result > 0){
            if(redisCache.hasKey(SYS_POST_KEY)){
                redisCache.deleteObject(SYS_POST_KEY);
            }
        }
    }
}
